﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using Utils.Wpf;

namespace StockAnalyst2.Plugins.Visualization.Historical
{
	internal class CustomDataViewerVM
	{
		#region Attributes

		private readonly ObservableCollection<FrameworkElement> _data;

		#endregion

		#region Properties

		public ObservableCollection<FrameworkElement> Data
		{
			get
			{
				return _data;
			}
		}

		public FrameworkElement SelectedItem { get; set; }
		public ICommand CopyCommand { get; private set; }
		public ICommand ExportToFileCommand { get; private set; }

		#endregion

		#region Events

		public event EventHandler<SaveFileDialogRequestedEventArgs> SaveFileDialogRequested;

		#endregion

		#region Public Methods

		public CustomDataViewerVM(ObservableCollection<FrameworkElement> data)
		{
			_data = data;

			this.CopyCommand = new DelegateCommand(ExecuteCopy, CanCopy);
			this.ExportToFileCommand = new DelegateCommand(ExecuteExportToFile, CanExportToFile);
		}

		protected virtual void OnSaveFileDialogRequested(SaveFileDialogRequestedEventArgs e)
		{
			if (this.SaveFileDialogRequested != null)
			{
				this.SaveFileDialogRequested(this, e);
			}
		}

		#endregion

		#region Private Methods

		private void ExecuteCopy()
		{
			ControlRenderer renderer = new ControlRenderer(96, 96);
			Clipboard.SetImage(renderer.Render(this.SelectedItem));
		}

		private bool CanCopy()
		{
			return this.SelectedItem != null;
		}

		private void ExecuteExportToFile()
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog() { Title = "Export to file ...", AddExtension = true, DefaultExt = "jpg", Filter = "Jpeg Files|*.jpg|All Files|*.*" };
			SaveFileDialogRequestedEventArgs e = new SaveFileDialogRequestedEventArgs(saveFileDialog);
			this.OnSaveFileDialogRequested(e);
			
			if (e.DialogResult != null && e.DialogResult.Value) 
			{
				using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
				{
					ControlRenderer renderer = new ControlRenderer(96, 96);
					JpegBitmapEncoder encoder = new JpegBitmapEncoder() {QualityLevel = 100};
					encoder.Frames.Add(BitmapFrame.Create(renderer.Render(this.SelectedItem)));
					encoder.Save(stream);					
				}
			}
		}

		private bool CanExportToFile()
		{
			return this.SelectedItem != null;
		}

		#endregion
	}
}
